//
//  UserShareListController.m
//  HappyBaby
//
//  Created by 华哥 on 15/11/28.
//  Copyright © 2015年 华哥. All rights reserved.
//

#import "UserShareListController.h"
#import "Define.h"
#import "UserShareListCell.h"
#import <BmobSDK/Bmob.h>
#import "UserShareDetailController.h"
#import "UserShareController.h"


@interface UserShareListController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) UITableView *tableView;
@end

static NSString *cellIndentifier = @"cell";
@implementation UserShareListController



- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.modelArray = [NSMutableArray array];
    [self createView];

    [self achieveDataFromService];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithTitle:@"发表" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction)];
    self.navigationItem.rightBarButtonItem = rightBarButton;    
}
- (void)rightBarButtonAction
{
    UserShareController *userShare = [[UserShareController alloc]init];
    [self.navigationController pushViewController:userShare animated:YES];
}

- (void)createView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 49) style:UITableViewStylePlain];
    [self.tableView registerClass:[UserShareListCell class] forCellReuseIdentifier:cellIndentifier];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = NO;
    [self.view addSubview:self.tableView];
}

#pragma mark ------------------------ TableView 设置 -----------------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.modelArray.count == 0)
    {
        return 0;
    }
    else
    {
        return self.modelArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserShareListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    UserShareModel *model = self.modelArray[indexPath.row];
    cell.model = model;
    return cell;
}

// 添加cell跳转到详情界面;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserShareModel *model = self.modelArray[indexPath.row];
    UserShareDetailController *userShareDetail = [[UserShareDetailController alloc]init];
    userShareDetail.model = model;
    userShareDetail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:userShareDetail animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserShareModel *userShareModel = self.modelArray[indexPath.row];
//    CGRectMake(30, self.shareTitle.y + self.shareTitle.height, kScreenWidth - 60, 60)
    CGSize shareContentSize = [self stringSizeWithFont:[UIFont systemFontOfSize:15 weight:1] string:userShareModel.shareContent width:kScreenWidth - 60];
    if (userShareModel.shareImage.length == 0)
    {
        if (shareContentSize.height < 30)
        {
            return 130 + shareContentSize.height + 20 + 50;
        }
        else
        {
            return 130 + 30 + 20 + 50;
        }      
    }
    else
    {
        if (shareContentSize.height < 30)
        {
            return 130 + shareContentSize.height + 80  + 20 + 50;
        }
        else
        {
            return 130 + 30 + 80 + 20 + 50;
        }
    }
}

- (CGSize)stringSizeWithFont:(UIFont *)font string:(NSString *)string width:(CGFloat)width
{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    return rect.size;
}

#pragma mark --------------------  从服务器获取数据 -----------------------------
- (void)achieveDataFromService
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"UserPublic"];
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error)
        {
            NSLog(@"error === %@",error);
        }
        else
        {
            for (int i = 0; i < array.count; i++)
            {
                BmobObject *obj = array[i];
                UserShareModel *model = [[UserShareModel alloc]init];
                
                // 用户信息
                model.userInfoModel.username = [obj objectForKey:@"username"];
                BmobFile *userHeadImage = [obj objectForKey:@"userHeadImage"];
                model.userInfoModel.userHeadImage = userHeadImage.url;
                
                // 分享信息
                model.shareTitle = [obj objectForKey:@"userShareTitle"];
                model.shareContent = [obj objectForKey:@"shareContent"];
                BmobFile *shareImage = [obj objectForKey:@"shareImage"];
                model.shareImage = shareImage.url;
                
                model.shareComment = [obj objectForKey:@"shareComment"];
                
                model.objectId = [obj objectForKey:@"objectId"];
                
//                model.publishTime = [obj objectForKey:@"createdAt"];
                
                [self.modelArray addObject:model];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }];
}
            
//压缩图片封装方法
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    // Now we get the full path to the file
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];
}

- (NSString *)documentFolderPath
{
    NSLog(@"documentFolderPath ==== %@",[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]);
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}





















@end
